﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Configuration;
using JLL.China.Infrastructure.Services;
using System.IO;
using JLL.China.Web.Libraries;
using System.Drawing;
using JLL.China.Application;
using JLL.China.Web.Areas.Portal.Models;
using System.Web;

namespace JLL.China.Web.Areas.Portal.Controllers
{
    public class ContentController : Controller
    {
        //
        // GET: /Portal/Content/
        protected int defaultPageSize = Int32.Parse(WebConfigurationManager.AppSettings["page_size_default"]);
    
        protected Model.Admin loginAcc;
        
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ChangeNumOfRow(FormCollection f)
        {
            Session["page_size_default"] = f["display_show_page"].ToString();
            Session["message"] = "Changed number of row";
            return RedirectToAction("Index");
        }
        void ShowMessage(string msg, string type)
        {
            Session["message"] = msg;
            Session["messageType"] = type;
        }
        public bool checkUserLogin()
        {
            var loginAcc = this.Session[Constants.Session_User] as Model.Admin;
            if (loginAcc == null)
            {
                return false;
            }
            return true;
        }
        //Step 1
        public ActionResult Step1(decimal? id)
        {
            //            ViewData["newscount"] = Session["newscount"];
            /* ViewData["CategoryID"] = 1;
             Session["CategoryID"] = 1;*/
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            string ControllerName = this.ControllerContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString(); ;
            //News
            if (ControllerName == "News")
            {
                ViewData["ActionPost"] = "News";
            }
            //Researches
            if (ControllerName == "Researches")
            {
                ViewData["ActionPost"] = "Researches";
            }
            //Services
            if (ControllerName == "Services")
            {
                ViewData["ActionPost"] = "Services";
            }
           
            if (id != null)
            { //for edit
                PortalModel model = new PortalModel();
                model.NewsModel = NewsService.FindByID_Language(id, 1);
                model.NewsModel_Local = NewsService.FindByID_Language(id, 2);
                return View("../Content/Create", model);

            }
            else
            {

                return View("../Content/Create");
            }
        }

        string CreateSlug(string s)
        {
            string str = "-";
            s = s.Replace("/", str);
            s = s.Replace(" ", str);
            s = s.Replace("%", str);
            return s;
        }

        public ActionResult ShowThumbnail(decimal id)
        {
            var imageData = NewsService.GetThumbnail(id);
            if (imageData == null)
            {
                //return new FilePathResult("~/Content/Images/NoPhoto.png", "image/png");
                string filePath = Server.MapPath("~/Content/images/no_img_default.png");
                string fileName = Path.GetFileName(filePath);
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);
                var eximg = br.ReadBytes((Int32)fs.Length);
                return File(eximg, "image/jpg");
            }
            else
            {

                return new FileContentResult(imageData.ToArray(), "image/jpeg");
            }
            //return File( imageData, "image/jpg" );
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Step1(Portal.Models.PortalModel model, HttpPostedFileBase thumnail)
        {

            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            var loginAcc = this.Session[Constants.Session_User] as Model.Admin;
            if (loginAcc == null)
            {
                return RedirectToAction("Login", "Home", new { area = "" });
            }
            if (model.NewsModel.NewsId == null) //insert
            {

                model.NewsModel.DateCreated = DateTime.Now;
                model.NewsModel.CreatedBy = loginAcc.UserName;
                string ControllerName= this.ControllerContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();;
                //News
                if (ControllerName == "News")
                {
                    model.NewsModel.NewCategoryFID = 1;
                }
                //Researches
                if (ControllerName == "Researches")
                {
                    model.NewsModel.NewCategoryFID = 2;
                }
                //Services
                if (ControllerName == "Services")
                {
                    model.NewsModel.NewCategoryFID = 3;
                }
                model.NewsModel.LanguageFID = 1;
                model.NewsModel_Local.LanguageFID = 2;
                model.NewsModel.Slug = CreateSlug(model.NewsModel.Title);
                if (thumnail != null)
                {
                    BinaryReader b = new BinaryReader(thumnail.InputStream);
                    byte[] binData = b.ReadBytes(thumnail.ContentLength);
                    Image orig = HelperUtility.byteArrayToImage(binData);
                    var imgthumb = HelperUtility.imageToByteArray(HelperUtility.GetThumbImage(orig, 120, orig.Width, orig.Height));
                    model.NewsModel.Thumbnail = imgthumb;
                }

                model.NewsModel_Local.Slug = CreateSlug(model.NewsModel_Local.Title);
                NewsService.CreateNews(model.NewsModel, model.NewsModel_Local);
                //                Session["message"] = "Records updated successfully.";
                //                Session["messageType"] = "Success";
                // return View("../Content/Create");
            }
            else //for update
            {
                model.NewsModel.UpdatedBy = loginAcc.UserName;
                model.NewsModel.DateUpdated = DateTime.Now;
                model.NewsModel.LanguageFID = 1;
                model.NewsModel_Local.LanguageFID = 2;
                model.NewsModel.Slug = CreateSlug(model.NewsModel.Title);
                if (thumnail != null)
                {
                    BinaryReader b = new BinaryReader(thumnail.InputStream);
                    byte[] binData = b.ReadBytes(thumnail.ContentLength);
                    Image orig = HelperUtility.byteArrayToImage(binData);
                    var imgthumb = HelperUtility.imageToByteArray(HelperUtility.GetThumbImage(orig, 120, orig.Width, orig.Height));
                    model.NewsModel.Thumbnail = imgthumb;
                }
                model.NewsModel_Local.Slug = CreateSlug(model.NewsModel_Local.Title);
                NewsService.UpdateNews(model.NewsModel, model.NewsModel_Local);
                //                Session["message"] = "Records updated successfully.";
                //                Session["messageType"] = "Success";
            }
            ShowMessage("Saved successfully.", "Success");

            return RedirectToAction("Index");


        }

        public ActionResult ChangeStatus(decimal id, bool status)
        {
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }

            /* var model = NewsService.FindByID_Language(id,1);
             model.UpdatedBy = loginAcc.UserName;
             model.DateUpdated = DateTime.Now;
             var model_local = NewsService.FindByID_Language(id, 2);
            

             model.Status = model.Status ? false : true;

             NewsService.UpdateNews(model,model_local);*/
            NewsService.ChangeStatus(id.ToString(), !status);
            ShowMessage("Saved successfully.", "Success");

            return RedirectToAction("Index", new { page = Session["pageindex"] });
        }
        

        public ActionResult Delete(decimal? id)
        {
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            decimal res = -1;
            if (id != null)
                res = NewsService.DeleteNews(id);
            if (res != -1)
            {
                //                Session["message"] = "Records updated successfully.";
                //                Session["messageType"] = "Success";
                ShowMessage("Deleted successfully.", "Success");
            }
            else
            {
                //                Session["message"] = "Records updated unsuccessfully.";
                //                Session["messageType"] = "Error";
                ShowMessage("Deleted unsuccessfully.", "Error");
            }
            return RedirectToAction("Index/1?page=" + Session["pageindex"].ToString());
        }

       
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult BulkProcess(string id, IEnumerable<int> selected)
        {

            try
            {
                string arr_id = "0";
                foreach (var key in selected)
                {
                    arr_id += "," + key.ToString();
                }
                //
                if (id == "Active")
                {

                    NewsService.ChangeStatus(arr_id, true);
                    Session["message"] = "Saved successfully.";
                    return RedirectToAction("Index/1?page=" + Session["pageindex"].ToString());
                }
                //
                if (id == "Inactive")
                {
                    NewsService.ChangeStatus(arr_id, false);
                    Session["message"] = "Saved successfully.";
                    return RedirectToAction("Index/2?page=" + Session["pageindex"].ToString());
                }
                //
                if (id == "Delete")
                {
                    NewsService.RemoveSelected(arr_id);
                    Session["message"] = "Deleted successfully.";
                    return RedirectToAction("Index/3?page=" + Session["pageindex"].ToString());
                }

                return RedirectToAction("Index");
            }
            catch
            {

                return RedirectToAction("Index");
            }

            return RedirectToAction("Index/1?page=" + Session["pageindex"].ToString());
            //  return RedirectToAction("Index");
        }
    }
}
